from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,Http404

from myadmin.models import Users,Types,Goods,Cart,Address,Order,OrderInfo

# Create your views here.
#首页
def index(request):

    # #获取所有的二级菜单
    obs = Types.objects.exclude(pid = 0)
    

    # # 获取一级分类
    types = Types.objects.filter(pid=0)
    for x in types:
        #在一级分类中，添加sub里面放对应的二级数据
        x.sub = Types.objects.filter(pid=x.id)

    #分配数据
    context = {'tlist':obs,'types':types}

    return render(request,'home/index.html',context)

#列表
def list(request,tid):

    # 接收分类id,获取分类对象
    ob = Types.objects.get(id=tid)
    data = {}
    # 判断当前分类是一级还是二级
    if ob.pid == 0:
        # 顶级分类 手机
        data['parent'] = ob
        # 获取当前类下子类
        data['typelist'] = Types.objects.filter(pid=ob.id)
        # 获取当前所有分类下的商品
        data['goodslist'] = Goods.objects.filter(tid__in=data['typelist'])

    else:
        # 二级分类 魅族,魅蓝
        data['parent'] = Types.objects.get(id=ob.pid)
        # 获取当前父类下子类
        typelist = Types.objects.filter(pid=data['parent'].id)
        # 循环当前所有子类,确定是否为当前类,追加属性
        for x in typelist:
            if x.id == ob.id:
                x.selected = True
        data['typelist'] = typelist
        # 获取当前分类下的商品
        data['goodslist'] = Goods.objects.filter(tid=ob.id)

    # 获取所有的二级菜单
    obs = Types.objects.exclude(pid = 0)
    # 分配数据
    context = {'tlist':obs,'data':data}

    return render(request,'home/list.html',context)
 
#详情
def info(request,gid):

    #根据商品id，获取商品信息
    try:
        ob = Goods.objects.get(id=gid)
        #增加点击量
        ob.clicknum += 1
        ob.save()

        # 获取所有的二级菜单
        obs = Types.objects.exclude(pid = 0)
        # 分配数据
        context = {'tlist':obs,'ginfo':ob}

        return render(request,'home/info.html',context)
    
    except:
        raise Http404("纳尼,怎么不见了?")


#购物车添加
def cartadd(request):
    try:
        # 用户id,商品id,购买数量num
        data = {}
        data['uid'] = Users.objects.get(id=request.session['VipUser']['uid'])
        data['gid'] = Goods.objects.get(id=request.GET.get('gid'))
        data['num'] = request.GET.get('num')

        # 根据用户id,判断当前用户的购物车中是否加入了当前的商品
        res = Cart.objects.filter(uid=data['uid']).filter(gid=data['gid'])
        if res :
            # 如果有这个商品,则修改数量
            res[0].num += int(data['num'])
            res[0].save()
        else:
            # 没有这个商品.,添加到购物车
            ob = Cart.objects.create(**data)

        return JsonResponse({'code':0,'msg':'添加购物车成功'})
    except:
        return JsonResponse({'code':1,'msg':'添加购物车失败'})

#购物车列表
def cartindex(request):
    # 需要根据用户id获取当前用户购物车的信息
    data = Cart.objects.filter(uid=request.session['VipUser']['uid'])
    

    # 分配数据
    context = {'cartlist':data,'tlist':Types.objects.exclude(pid = 0)}
    # 加载模板
    return render(request,'home/cart.html',context)


# 购物车商品的数量更新
def cartedit(request):
    try:
        # 商品id,商品最新数量
        gid = request.GET['gid']
        num = request.GET['num']

        print(gid,num)
        # print(type(gid),type(num))

        # 获取购物车数据对象
        obs = Cart.objects.filter(uid=request.session['VipUser']['uid']).filter(gid=gid)[0]
        obs.num = int(num)
        obs.save()

     
        return JsonResponse({'code':0,'msg':'购物车数量更新成功'})
    except:
        return JsonResponse({'code':1,'msg':'购物车数量更新失败'})


#删除购物车商品
def cartdel(request):
    kid = request.GET['kid']
    obs = Cart.objects.get(id=kid)

    obs.delete()

    return JsonResponse({'msg':'购物车数量更新成功'})



# 确认订单
def confirmorder(request):
    # 获取已经选择的购物车的商品
    ids = eval(request.GET['ids'])
    # 根据选择的购物车商品，获取对象，显示到页面中
    obs = Cart.objects.filter(id__in=ids)

    # 分配数据
    context = {'cartlist':obs}

    # 加载模版
    return render(request,'home/confirmorder.html',context)

# 添加新地址
def addressinsert(request):
    # 接受参数
    data = request.POST.dict()
    ids = data['ids']
    del data['csrfmiddlewaretoken']
    del data['ids']
    # 获取用户对象
    data['uid'] = Users.objects.get(id=request.session['VipUser']['uid'])

    # 执行地址添加
    ob = Address.objects.create(**data)

    return HttpResponse('<script>location.href="/confirm/order/?ids='+ids+'"</script>')


# 设置默认地址
def addressset(request):
    # 接受id,获取用户id,在修改
    aid = request.GET['aid']
    uid = request.session['VipUser']['uid']

    # 先获取当前用户的所有地址
    obs = Address.objects.filter(uid=uid)
    obs.update(isSelect=0)
    ob = obs.get(id=aid)
    ob.isSelect = True
    ob.save()

    return HttpResponse('addressset')


# 订单的提交 创建订单
def orderinsert(request):
    # 获取数据
    data = request.POST.dict()
    # 计算总价
    totalprice = 0
    for x in eval(data['ids']):
        cart = Cart.objects.get(id=x)
        totalprice += cart.num * cart.gid.price



    # 准备创建订单
    ob = Order()
    # 获取用户对象
    ob.uid = Users.objects.get(id=request.session['VipUser']['uid'])
    # 获取地址对象
    ob.addressid = Address.objects.get(id=data['addressid'])
    # 设置总价
    ob.totalprice = totalprice
    # 设置状态
    ob.status = 1
    # 执行添加
    ob.save()

    # 创建订单详情
    for x in eval(data['ids']):
        # 购物车对象
        cart = Cart.objects.get(id=x)
        # 执行订单详情的创建
        order = OrderInfo()
        order.orderid = ob
        order.goodsid = cart.gid
        order.num = cart.num
        order.price = cart.gid.price
        order.save()
        # 在购物车中删除已下单的购物车商品
        cart.delete()


    # 注意:在创建订单的视图函数中,不能直接返回模板,而是要重定向到其它位置
    # 要避免当前请求重复提交 因为这个请求是post发送,并且视图函数中在创建订单,

    # 跳转到 付款  页面
    return HttpResponse('<script>alert("订单创建成功,请付款");location.href="/buyjia/'+str(ob.id)+'/"</script>')

#付款页面
def buyjia(request,oid):
    
    # 根据订单id,获取订单信息,显示支付页面
    order = Order.objects.get(id=oid)

    context = {'order':order}

    return render(request,'home/buy.html',context)


#我的订单
def myorders(request):
    gids =5
    if 'id' in request.GET :
        gids = int(request.GET['id'])    

    if gids<5 :
        orders = Order.objects.filter(uid=request.session['VipUser']['uid'],status=gids)
    else :    
        #根据session的用户id，获取当前用户的所有订单
        orders = Order.objects.filter(uid=request.session['VipUser']['uid'])          


    #分配数据
    context = {'orders':orders,'gid':gids}

    return render(request,'home/myorder.html',context)






#注册
def register(request):
    if request.method == 'GET':

        return render(request,'home/register.html')
    
    elif request.method == 'POST':
        #获取数据
        data = request.POST.dict()
        del data['csrfmiddlewaretoken']

        #验证手机号和验证码是否正确
        if data['phone'] == request.session['sendsms']['phone'] and data['code'] == request.session['sendsms']['code']:
            #进行密码加密
            from django.contrib.auth.hashers import make_password,  check_password
            data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

        try:

            del data['code']
            #执行注册
            ob = Users.objects.create(**data)
            return HttpResponse('<script>alert("注册成功，请登录");location.href="/login/"</script>')

        except:
            return HttpResponse('<script>alert("注册失败");location.href="/register/"</script>')

    else:
        return HttpResponse('<script>alert("验证码错误");location.href="/register/"</script>')

#登陆
def login(request):
    #获取上一次请求路径
    nextpath = request.GET.get('next','/')

    if request.method == 'GET':

        return render(request,'home/login.html')
    elif request.method == 'POST':

        #获取数据
        data = request.POST.dict()
        del data['csrfmiddlewaretoken']
        
        #先判断手机号用户是否存在
        try:
            ob = Users.objects.get(phone = data['phone'])

            #检测密码是否正确
            #判断密码
            from django.contrib.auth.hashers import check_password
            #检测密码
            if check_password(data['password'],ob.password):
                #执行登录
                request.session['VipUser'] = {'uid':ob.id,'uname':ob.username,'phone':ob.phone,'pic':ob.pic}
                return HttpResponse('<script>alert("欢迎登录");location.href="'+nextpath+'"</script>')
        except:
            pass
        
        return HttpResponse('<script>alert("用户名或密码错误");history.back(-1);</script>')


#短信测试
def sendsms(request):
    from dysms import demo_sms_send
    import random

    #获取手机号
    phone = request.GET['phone']
    #随机验证码
    code = random.randrange(1000,9999)
    print(code)
    print(phone)

    #把随机的验证码存入session
    request.session['sendsms'] = {'phone':phone,'code':str(code)}
    
    #执行验证码的发送
    res = demo_sms_send.send(str(code),phone)
    res = eval(res)

    print(res)

    if res['Code'] == 'OK':
        #发送成功
        return JsonResponse({'code':0,'msg':'发送成功'})
    else:
        #发送失败
        return JsonResponse({'code':1,'msg':'发送失败','error':res['Message']})